<?php

require_once 'phpQuery/phpQuery.php';
# 调试模式
defined('DEBUG') or define('DEBUG', false);
# 时间戳
define('NOW_TIME', $_SERVER['REQUEST_TIME']);
define('NOW_DATE', date('YmdHis', NOW_TIME));

# 基础路径
define('BASE_PATH', dirname(__FILE__) . '/');
# 缓存目录
define('CACHE_PATH', BASE_PATH . 'cache/');
define('CACHE_EXPIRE', 86400);


#
date_default_timezone_set('Asia/Shanghai');
if (DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}
set_time_limit(0);


/**
 * 发起一个请求
 * @param $url
 * @param string $referer
 * @return bool|mixed|string
 */
function _request($url, $referer = '', $expire = CACHE_EXPIRE)
{
    if (($content = _GetCache($url, $expire)) && $expire >= 0) {
        return $content;
    }
    $url = _getFullUrl($url, $referer);
    $pus = parse_url($url);
    $host = isset($pus['host']) ? $pus['host'] : '';
    $cookie = dirname(__FILE__) . '/cookie/' . $host . '.cookie';
    if (function_exists('curl_init')) {
        //var_dump($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        //Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER');


        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);

        if (is_string($referer)) {
            curl_setopt($ch, CURLOPT_REFERER, $referer ? $referer : $url);
        } elseif (is_array($referer)) {
            foreach ($referer as $key => $value) {
                @curl_setopt($ch, $key, $value);
            }
        }

        $result = curl_exec($ch);
        curl_close($ch);
    } elseif (version_compare(PHP_VERSION, '5.0.0') >= 0) {
        $opts = array(
            'http' => array(
                'header' => "Referer:{$url}"
            )
        );
        $result = file_get_contents($url, false, stream_context_create($opts));
    } else {
        $result = file_get_contents($url);
    }
    if ($expire >= 0)
        _SetCache($url, $result);
    return $result;
}


function _CacheFileName($name)
{
    $name = md5(serialize($name));
    return substr($name, 0, 2) . '/' . $name . '.cache';
}

function _CacheFullFileName($name)
{
    $full_name = CACHE_PATH . _CacheFileName($name);
    $full_path = dirname($full_name);
    if (!is_dir($full_path)) {
        @mkdir($full_path, 0777, true);
    }
    return $full_name;
}


/**
 * 判断是否缓存
 * @param $name
 * @param int $expire
 */
function _isCache($name, $expire = 0)
{
    $filename = _CacheFullFileName($name);
    if ($expire > 0) {
        //判断过期时间
        $mtime = @filemtime($filename);
        if (time() - $mtime > $expire) {
            @unlink($filename);
            return false;
        }

    }
    return is_file($filename);
}

/**
 * 缓存
 * @param $name
 * @param $data
 * @param int $expire
 */
function _SetCache($name, $data)
{
    $filename = _CacheFullFileName($name);
    $ser_data = $data;//serialize();
    return file_put_contents($filename, $ser_data);
}

function _GetCache($name, $expire = 0)
{
    if (_isCache($name, $expire)) {
        $filename = _CacheFullFileName($name);
        $data = file_get_contents($filename);
        return $data;//serialize($data);
    }
    return null;
}


/**
 * 判断是否为url
 * @param $str
 * @return bool
 */
function _isURL($str)
{
    if (preg_match('/^http(s)?:\\/\\/.+/', $str)) {
        return true;
    }
    return false;
}

/**
 * 获取到完整的url
 * @param $url
 * @param string $referer
 * @return string
 */
function _getFullUrl($url, $referer = '')
{
    //判断 url 是否完整url地址
    if (_isURL($url)) return formatUrl($url);

    //如果不是完整地址
    //判断referer 是否完整
    if (!_isURL($referer)) {
        return $url;
    }
    $pus = parse_url($referer);
    $base = formatUrl($pus['scheme'] . '://' . $pus['host']);
    $path = formatUrl(dirname($pus['path']));

    if (substr($url, 0, 1) === '/') {//回到根
        return formatUrl($base . $url);
    }
    if (substr($url, 0, 2) === './') {//当前目录
        return formatUrl($base . $path . '/' . substr($url, 2));
    }
    if (substr($url, 0, 3) === '../') {//上级目录
        $_url = $path . '/' . $url;
        while (strpos($_url, '../') !== false) {
            $_url = preg_replace('/\/[^\/]*\/..\/|\/..\//', '/', $_url);
        }
        return formatUrl($base . '/' . $_url);
    }
    return formatUrl($base . $path . '/' . $url);
}


function _set_url($url, $options = array(), &$ret = array())
{
    $url = str_replace('&amp;', '&', $url);
    $url_info = parse_url($url);
    $keys = array('scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment');
    $new_url = '';
    foreach ($options as $key => $o) {
        if (in_array($key, $keys)) {
            $_v = isset($url_info[$key]) ? $url_info[$key] : '';
            if ('query' == $key) {
                //解析query值
                parse_str($_v, $_query);
                if (!is_array($o)) {
                    parse_str('' . $o, $o);
                }
                //将新值注入到query 中
                foreach ($o as $_k => $__v) {
                    $_query[$_k] = $__v;
                }
                $o = http_build_query($_query);
            }
            $url_info[$key] = $o;
        }
    }

    if (isset($url_info['scheme']) && $url_info['scheme']) {
        $new_url .= $url_info['scheme'] . '://';
    } else {
        $new_url .= 'http://';
    }
    if (isset($url_info['user']) && $url_info['user']) {
        $new_url .= $url_info['user'];
        if (isset($url_info['pass']) && $url_info['pass']) {
            $new_url .= ':' . $url_info['pass'];
        }
        $new_url .= '@';
    }
    if (isset($url_info['host']) && $url_info['host']) {
        $new_url .= $url_info['host'];
    }
    if (isset($url_info['port']) && $url_info['port']) {
        $new_url .= ':' . $url_info['port'];
    }
    if (isset($url_info['path']) && $url_info['path']) {
        $new_url .= $url_info['path'];
    }
    if (isset($url_info['query']) && $url_info['query']) {
        $new_url .= '?' . $url_info['query'];
    }
    if (isset($url_info['fragment']) && $url_info['fragment']) {
        $new_url .= '#' . $url_info['fragment'];
    }
    $ret = $url_info;
    return formatUrl($new_url);
}


function isTel($tel)
{
    if (!is_string($tel)) {
        return false;
    }
    return preg_match('/^[1-9][0-9]{10}$/', $tel);
}


/**
 * 格式化url
 * @param $url
 * @return mixed
 */
function formatUrl($url)
{
    $url = str_replace('\\', '/', $url);
    $url = preg_replace_callback('/(:?)([\/]{2,})/', function ($match) {
        //var_dump($match);
        if ($match[1] != ':') {
            return '/';
        } else {
            return $match[0];
        }
    }, $url);
    return $url;
}

/**
 * 输出日志
 * @param $msg
 * @param string $status
 */
function _Log($msg, $status = 'note')
{

    _write_html_frame();
    $time = date('Y-m-d H:i:s.t ');
    $id = _Log_id();
    $msg = '[' . $id . '].' . $time .' &nbsp; &nbsp; ' . trim($msg);
    $msg = str_replace('\'', '\\\'', $msg);
    $msg = str_replace("\n", '<br/>', $msg);
    $msg = str_replace("\r", '', $msg);
    $mid = 'log-script-' . $id;
    echo '<script id="' . $mid . '">
    _Log(\'' . $msg . '\',\'' . $status . '\');
    window.logScriptIitme = document.getElementById(\'' . $mid . '\');
    window.logScriptIitme.parentNode.removeChild(window.logScriptIitme);
    </script>';
    //ob_flush();
    flush();
}

/**
 * 日志编号
 * @return string
 */
function _Log_id($len = 10)
{
    static $id = 0;
    $id++;
    $_id = $id . '';
    $_len = $len - strlen($_id);
    return str_repeat('0', $_len) . $_id;

}


/**
 * 输出网页框架
 * @param string $title
 */
function _write_html_frame($title = '网页标题')
{
    static $writed = false;
    if (!$writed) {
        $writed = true;
        echo '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>' . $title . '</title>
    <style>
        #logBody{
            background: #000;
            padding: 10px;
            width: 800px;
            height: 600px;
            color: #FFF;
            font-family: "Microsoft YaHei", "微软雅黑", "宋体", Arial, sans-serif;
            font-size: 14px;
            line-height: 21px;
            margin:  30px auto;
            overflow: hidden;
            overflow-y: auto;
        }
        #logBody .item{
            padding: 5px 0px;
        }
        #logBody .item.error{
            color: red;
        }
        #logBody .item.success{
            color: green;
        }
        #logBody .item.note{
            color: yellow;
        }
    </style>
</head>
<body>
<div id="logBody"></div>
</body>
<script>
    var logBody = document.getElementById(\'logBody\');
    function _Log(msg,status){
        var item = document.createElement(\'div\');
        item.className = \'item \'+ ("" + status).toLowerCase();
        item.innerHTML = msg;
        logBody.appendChild(item);
        if(logBody.scrollHeight)
        logBody.scrollTop=logBody.scrollHeight+100;
    }
    _Log(\'网页加载完成！\',\'note\'); 
</script>
</html>';
    }
}


?>